import precisionCompute from '@/utils/bignumber'

/**
 * 数据格式处理
 * @param {*} value 数值
 * @param {*} unit 单位
 * @param {*} decimal 小数位
 * @param {*} showUnit 是否显示单位
 * @param {*} showType 展示类型 thousands（千分位）
 */
const formatData = ({ value, unit, decimal, showUnit, showType }) => {
  let val = parseFloat(value)

  if (isNaN(val)) {
    return value
  }

  if (unit === '%') {
    val = precisionCompute(val, '*', 100, decimal)
  } else if (['bp', 'BP', '万', '万元'].includes(unit)) {
    val = precisionCompute(val, '/', 1e4, decimal)
  } else if (unit === '百万') {
    val = precisionCompute(val, '/', 1e6, decimal)
  } else if (['亿', '亿元'].includes(unit)) {
    val = precisionCompute(val, '/', 100000000, decimal)
  }
  if (showType === 'thousands') {
    val = thousandFormat(precisionCompute(val, '*', 1, decimal))
  }

  return `${val}${showUnit ? unit : ''}`
}

/**
     * value 数值
     * decimal 小数位
     */
function thousandFormat(value, decimal) {
  const val = parseFloat(value)
  if (isNaN(val)) {
    return value
  }
  const strVal = String(value)
  const hasDot = strVal.indexOf('.') !== -1

  if (hasDot) {
    const valNum = strVal.substring(0, strVal.indexOf('.'))
    const dotNum = strVal.substring(strVal.indexOf('.') + 1, strVal.length)
    const intNum = String(valNum).replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
    return intNum + '.' + dotNum
  }

  return strVal.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
}

export default formatData
